#!/bin/bash
# Job yaml can send below ENVIRONMENT VARIABLES to me
# - group_id
# END ENVIRONMENT VARIABLES

. $LKP_SRC/lib/upload.sh

. $LKP_SRC/lib/job.sh
load_job_vars os id result_root SRV_HTTP_RESULT_HOST LKP_SERVER RESULT_WEBDAV_HOST SCHED_HOST DATA_API_PORT

prepare_env()
{
	gem install bundle
	cat <<-EOF >> /root/Gemfile
	source 'https://gems.ruby-china.com'

	gem 'rest-client', '= 2.1.0'
	gem 'bigdecimal', '= 1.3.4'
	EOF
	bundle install --gemfile=/root/Gemfile
}

get_results() {
    cd $TMP

    # 获取作业信息并筛选同一 testsuite 的最新 job
    env SCHED_HOST=$SCHED_HOST DATA_API_PORT=$DATA_API_PORT cci jobs group_id=${group_id} -f id,program.mugen.testsuite,start_time,job_stage,job_health,result_root | grep "/result/mugen/" > temp_output
    awk '
    {
        job_id = $1
        testsuite = $2
        start_time = $3
        job_stage = $4
        job_health = $5
        result_root = $6

        # 只处理 job_stage 为 finish 的记录
        if (job_stage == "finish") {
            if (!(testsuite in latest)) {
                latest[testsuite]["start_time"] = start_time
                latest[testsuite]["job_health"] = job_health
                latest[testsuite]["result_root"] = result_root
                latest[testsuite]["job_id"] = job_id
            } else {
                # 处理优先级：有值的 start_time 优先于空值
                if (start_time != "" && (latest[testsuite]["start_time"] == "" || start_time > latest[testsuite]["start_time"])) {
                    latest[testsuite]["start_time"] = start_time
                    latest[testsuite]["job_health"] = job_health
                    latest[testsuite]["result_root"] = result_root
                    latest[testsuite]["job_id"] = job_id
                }
            }
        }
    }
    END {
        for (ts in latest) {
            print latest[ts]["job_id"], ts, latest[ts]["start_time"], latest[ts]["job_health"], latest[ts]["result_root"]
        }
    }
    ' temp_output > filtered_output

    printf "%-40s%-15s%-15s%-15s%-15s%-15s\n" "testsuite" "success_num" "failed_num" "skipped_num" "job_id" "job_health" "result_dir" >> summary.txt

    while read job_id testsuite start_time job_health job_result_root; do
        rm -rf logs.tar
        rm -rf results results.tar

        if [ -z "${job_health}" ]; then
            job_health="[empty]"
        fi

        if [ "${job_health}" = "success" ]; then
            wget --no-check-certificate https://${SRV_HTTP_RESULT_HOST}:20007/${job_result_root}/results/results.tar && \
            wget --no-check-certificate https://${SRV_HTTP_RESULT_HOST}:20007/${job_result_root}/results/logs.tar
            if [ $? -ne 0 ]; then
                echo "Cannot find results and logs in ${job_id}"
                success_num="[empty]"
                failed_num="[empty]"
                skipped_num="[empty]"
				printf "%-40s%-15s%-15s%-15s%-15s%-15s%-15s\n" "${testsuite}" "${success_num}" "${failed_num}" "${skipped_num}" "${job_id}" "${job_health}" "${job_result_root}" >> "$TMP/summary.txt"
				continue
            else
                tar -zxf results.tar || { echo "Failed to extract results.tar"; exit 1; }
                if [ -d "results/${testsuite}/succeed" ]; then
                    success_num=$(find "results/${testsuite}/succeed" -type f | wc -l)
                    for success_testcase in results/${testsuite}/succeed/*; do
                        printf "%-40s%-15s\n" "$(basename "$success_testcase")" "succeed" >> "$TMP/${testsuite}.txt"
                    done
                else
                    success_num=0
                fi

                if [ -d "results/${testsuite}/failed" ]; then
                    failed_num=$(find "results/${testsuite}/failed" -type f | wc -l)
                    for failed_testcase in results/${testsuite}/failed/*; do
                        printf "%-40s%-15s\n" "$(basename "$failed_testcase")" "failed" >> "$TMP/${testsuite}.txt"
                    done
                else
                    failed_num=0
                fi

                if [ -d "results/${testsuite}/skipped" ]; then
                    skipped_num=$(find "results/${testsuite}/skipped" -type f | wc -l)
                    for skipped_testcase in results/${testsuite}/skipped/*; do
                        printf "%-40s%-15s\n" "$(basename "$skipped_testcase")" "skipped" >> "$TMP/${testsuite}.txt"
                    done
                else
                    skipped_num=0
                fi

                tar -zxf logs.tar || { echo "Failed to extract logs.tar"; exit 1; }
                cp "${testsuite}.txt" logs/${testsuite}/
            fi
        else
            success_num="[empty]"
            failed_num="[empty]"
        fi
        printf "%-40s%-15s%-15s%-15s%-15s%-15s%-15s\n" "${testsuite}" "${success_num}" "${failed_num}" "${skipped_num}" "${job_id}" "${job_health}" "${job_result_root}" >> "$TMP/summary.txt"

    done < filtered_output

    tar -czf logs.tar logs || { echo "Failed to create logs.tar"; exit 1; }
}

upload_statistic_result()
{
	upload_one_curl $TMP/logs.tar ${result_root}/results/
	upload_one_curl $TMP/summary.txt ${result_root}/results/
}


prepare_env
get_results
upload_statistic_result

